
#***************************************************
  # 1.13.2022
  #Replication files for 
  #"Informal Work, Risk and Clientelism: Evidence from 223 Slums Across India"
  #British Journal of Political Science 
#***************************************************

library(cregg)
library(ggplot2)
library(readstata13)
library(dplyr)
library(forcats)

setwd("")

# Read in data 
informality <- read.dta13("r_conjoint.dta")

# Make features factors
informality$lcandidate_random_a <- as.factor(informality$lcandidate_random_a)
informality$lcandidate_random_b <- as.factor(informality$lcandidate_random_b)
informality$occlow <- as.factor(informality$occlow)

#Add factor labels
informality$lcandidate_random_a  <- factor(informality$lcandidate_random_a ,
                    levels = c(2, 0, 1, 3),
                    labels = c("Co-ethnic", "Congress", "BJP", "Educated"))

informality$lcandidate_random_b  <- factor(informality$lcandidate_random_b ,
                                           levels = c(4,0,1,2,3),
                                           labels = c("Support of NH leader", "Private benefits", "Better services", "Co-ethnic benefits", "Pro-poor schemes"))

informality$occlow <- factor(informality$occlow ,
                                           levels = c(1, 0),
                                           labels = c("Lower formality", "Higher formality"))

informality <- informality %>%
  dplyr::rename(Trait1 = lcandidate_random_a,
                Trait2 = lcandidate_random_b) %>%
  mutate(Trait2 = fct_relevel(
    Trait2,
    c(
      "Support of NH leader",
      "Better services",
      "Private benefits",
      "Pro-poor schemes",
      "Co-ethnic benefits"
    )
  )
  )
  
ff <- choice2 ~ Trait1 + Trait2

dd <- cj(informality, ff, id = ~ r_id, estimate = "mm", h0 = 0.5)

# estimate AMCEs
dd2 <- cj(informality, ff, id = ~ r_id)

head(dd2[c("feature", "level", "estimate", "std.error")], 20L)

# plot AMCEs
plot(dd2, legend_title = "", xlab = "")

ggsave("conjoint_plot1.png", width = 7, height = 4, unit = "in")

## subgroup analysis amce
xx <- cj(informality,
         choice2 ~ Trait1 + Trait2,
         id = ~ r_id,
         by = ~ occlow)

plot(xx, group = "occlow", vline = 0.0, legend_title = "", xlab = "") 

ggsave("conjoint_plot2.png", width = 7, height = 4, unit = "in")

